#import "JokePageView.h"
#import "DBManager.h"
#import "NetWorkManager.h"
#import "JokePageCell.h"
#import "JokeModel.h"
#import "JokeReplyCell.h"
#import "JokeReplyModel.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SBJsonParser.h"
#import "UserManager.h"

@implementation JokePageView

@synthesize owner,jokeManagerPlaying,jokeIndexPathDisplaying,cellPlaying;
@synthesize userStateLogin,userStateLogout,currentUserState;

-(id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if(self){
        //
    }
    return self;
}

-(id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if(self){
        CGRect realFrame = self.frame;
        realFrame.size.height = WINDOW_HEIGHT-39;
        realFrame.origin.y = -5;
        self.frame = realFrame;
        
        self.userStateLogin =[[JPVUserStateLogin alloc]init:self];
        self.userStateLogout =[[JPVUserStateLogout alloc]init:self];
        self.jokeIndexPathDisplaying = nil;
        
        cellPlaying = nil;
        
        self.userInteractionEnabled = YES;
    }
    return self;
}

- (void)dealloc {
    PP_RELEASE(mainTableContainer);
    PP_RELEASE(frontCell);
    PP_RELEASE(backCell);
    PP_RELEASE(mainTable);
    PP_RELEASE(jokeActionBarContainer);
    PP_RELEASE(jokeActionBar);
    PP_RELEASE(commentTips);
    PP_RELEASE(cellPlaying);
    PP_RELEASE(jokeManagerPlaying);
    PP_RELEASE(jokeIndexPathDisplaying);
    PP_RELEASE(userStateLogin);
    PP_RELEASE(userStateLogout);
    PP_RELEASE(indicator);
//    PP_RELEASE(jumper);
//    PP_RELEASE(leftArrow);
//    PP_RELEASE(rightArrow);
//    PP_RELEASE(finger);
    [super dealloc];
}

- (void)start:(BaseUIViewController<JokePageViewDelegate, JokePageCellDelegate> *)pOwner :(JokeManager *)pJokeManagerPlaying {
    self.jokeManagerPlaying = pJokeManagerPlaying;
    self.owner = pOwner;
    
    [jokeActionBar removeFromSuperview];
    NSArray *acitonNibList = [[NSBundle mainBundle] loadNibNamed:@"JokeActionBar" owner:self options:nil];
    jokeActionBar = [[acitonNibList objectAtIndex:0] retain];
    [jokeActionBarContainer addSubview:jokeActionBar];
    [jokeActionBar start:self];
    
    autoSelecting = YES;
    
    [backCell removeFromSuperview];
    [mainTable removeFromSuperview];
    [frontCell removeFromSuperview];
    
    NSArray *backNibList = [[NSBundle mainBundle] loadNibNamed:@"JokePageCell" owner:self options:nil];
    backCell = [[backNibList objectAtIndex:0] retain];
    backCell.hidden = YES;
    [mainTableContainer addSubview:backCell];
    
    mainTable = [[EasyTableView alloc] initWithFrame:CGRectMake(0, 0, mainTableContainer.frame.size.width, mainTableContainer.frame.size.height) numberOfColumns:1 ofWidth:mainTableContainer.frame.size.width];
    mainTable.delegate					= self;
    mainTable.tableView.scrollEnabled   = NO;
    mainTable.tableView.pagingEnabled   = NO;
    mainTable.tableView.bounces         = NO;
    mainTable.tableView.allowsSelection	= YES;
    mainTable.tableView.showsVerticalScrollIndicator = YES;
    mainTable.tableView.scrollsToTop    = NO;
    mainTable.tableView.separatorColor		= [UIColor clearColor];
    mainTable.tableView.backgroundColor     = [UIColor clearColor];
    mainTable.cellBackgroundColor			= [UIColor clearColor];
    [mainTableContainer addSubview:mainTable];
    
    indicator.frame = [self getIndicatorFrame:0];
    
    NSArray *frontNibList = [[NSBundle mainBundle] loadNibNamed:@"JokePageCell" owner:self options:nil];
    frontCell = [[frontNibList objectAtIndex:0] retain];
    frontCell.hidden = YES;
    [mainTableContainer addSubview:frontCell];
    
//    UIPanGestureRecognizer *recognizerPan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePanFrom:)];
//    [self addGestureRecognizer:recognizerPan];
//    [recognizerPan release];
    
    UISwipeGestureRecognizer *horizontalLeft = [[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(panLeft)] autorelease];
    horizontalLeft.direction = UISwipeGestureRecognizerDirectionLeft;
    [self addGestureRecognizer:horizontalLeft];
    
    UISwipeGestureRecognizer *horizontalRight = [[[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(panRight)] autorelease];
    horizontalRight.direction = UISwipeGestureRecognizerDirectionRight;
    [self addGestureRecognizer:horizontalRight];
    
    
    UILongPressGestureRecognizer *recognizerLong = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(handleLongPressFrom:)];
    [self addGestureRecognizer:recognizerLong];
    [recognizerLong release];
}

//暂时没用到
-(void)handlePanFrom:(UIPanGestureRecognizer *)recognizer{
    if( recognizer.state == UIGestureRecognizerStateBegan ){
        jumpingPoint = [recognizer locationInView:self];
        [owner baseHideComment];
        return;
    }
    CGPoint pt = [recognizer locationInView:self];
    float dx = abs(pt.x-jumpingPoint.x);
    float dy = abs(pt.y-jumpingPoint.y);
    float ang = atan2(dy,dx);
    if( ang > 0.45 ){
        return;
    }
    //    Log(@"angle : %f",ang);
    if( pt.x>jumpingPoint.x && pt.x-jumpingPoint.x>50){
        if(jumping){    
            jumping = NO;
            [self panRight];
        }
    }else if(jumpingPoint.x>pt.x && jumpingPoint.x-pt.x>50){
        if(jumping){
            jumping = NO;
            [self panLeft];
        }
    }else{
        jumping = YES;
    }
}

- (void)panLeft {
    if(jokeIndexPathDisplaying.row==jokeManagerPlaying.listShow.count - 1){
        [owner baseShowInfoHud:@"已经是最后一篇" andIsTop:NO];
        return;
    }
    frontCell.backgroundColor = UIColorFromRGB(0xebeef0, 1.0f);
    cellPlaying.backgroundColor = UIColorFromRGB(0xebeef0, 1.0f);
    backCell.backgroundColor = UIColorFromRGB(0xebeef0, 1.0f);
    autoSelecting = NO;
    backCell.hidden = NO;
    //展示层准备滑动，加边加底
    cellPlaying.backgroundColor = UIColorFromRGB(0xebeef0, 1.0f);
    [UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationCurveEaseOut animations:^(void){
        //展示层移动
        CGRect cellFrame = cellPlaying.frame;
        cellFrame.origin.x = -self.frame.size.width;
        cellPlaying.frame = cellFrame;
        indicator.frame = [self getIndicatorFrame:jokeIndexPathDisplaying.row+1];
    }completion:^(BOOL bl){
        //展示层准备复位，去边去底
        cellPlaying.backgroundColor = [UIColor clearColor];
        mainTable.hidden = YES;
        CGRect cellFrame = cellPlaying.frame;
        cellFrame.origin.x = 0;
        cellPlaying.frame = cellFrame;
        CGPoint offset = mainTable.tableView.contentOffset;
        offset.y = offset.y + self.frame.size.width;
        mainTable.tableView.contentOffset = offset;
        frontCell.backgroundColor = [UIColor clearColor];
        backCell.backgroundColor = [UIColor clearColor];
        cellPlaying.backgroundColor = [UIColor clearColor];
        //展示层已经复位，隐藏后层
        [UIView animateWithDuration:0.2 delay:0.0 options:UIViewAnimationCurveEaseOut animations:^(void){
            mainTable.alpha = 0.0f;
        }completion:^(BOOL bl){
            mainTable.hidden = NO;
            mainTable.alpha = 1.0f;
            backCell.hidden = YES;
            [self frontNback];
        }];
    }];
}

- (void)panRight {
    if(jokeIndexPathDisplaying.row==0){
        [owner baseShowInfoHud:@"已经是最新一篇" andIsTop:NO];
        return;
    }
    frontCell.backgroundColor = UIColorFromRGB(0xebeef0, 1.0f);
    cellPlaying.backgroundColor = UIColorFromRGB(0xebeef0, 1.0f);
    backCell.backgroundColor = UIColorFromRGB(0xebeef0, 1.0f);
    autoSelecting = NO;
    frontCell.hidden = NO;
    [UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationCurveEaseOut animations:^(void){
        CGRect leftFrame = frontCell.frame;
        leftFrame.origin.x = 0.5f;
        leftFrame.origin.y = -0.5f;
        frontCell.frame = leftFrame;
        indicator.frame = [self getIndicatorFrame:jokeIndexPathDisplaying.row-1];
    }completion:^(BOOL bl){
        frontCell.backgroundColor = [UIColor clearColor];
        CGPoint offset = mainTable.tableView.contentOffset;
        offset.y = offset.y - self.frame.size.width;
        mainTable.tableView.contentOffset = offset;
        frontCell.backgroundColor = [UIColor clearColor];
        backCell.backgroundColor = [UIColor clearColor];
        cellPlaying.backgroundColor = [UIColor clearColor];
        [UIView animateWithDuration:0.2 delay:0.0 options:UIViewAnimationCurveEaseOut animations:^(void){
            frontCell.alpha = 0.99f;
        }completion:^(BOOL bl){
            frontCell.hidden = YES;
            frontCell.alpha = 1.0f;
            [self frontNback];
        }];
    }];
}

-(void)handleLongPressFrom:(UILongPressGestureRecognizer *)recognizer{
    if( recognizer.state == UIGestureRecognizerStateBegan ){
        draggingPoint = [recognizer locationInView:self];
        dragging = YES;
        [owner baseHideComment];
        //        [self frontNback];
        frontCell.backgroundColor = UIColorFromRGB(0xebeef0, 1.0f);
        cellPlaying.backgroundColor = UIColorFromRGB(0xebeef0, 1.0f);
        backCell.backgroundColor = UIColorFromRGB(0xebeef0, 1.0f);
        frontCell.hidden = NO;
        cellPlaying.hidden = NO;
        backCell.hidden = NO;
        [UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationCurveEaseOut animations:^(void){
            CGRect frontFrame = frontCell.frame;
            frontFrame.origin.x = 0.5f-self.frame.size.width*3/4;
            frontFrame.origin.y = -0.5f;
            frontCell.frame = frontFrame;
            CGRect cellFrame = cellPlaying.frame;
            cellFrame.origin.x = -self.frame.size.width/4;
            cellPlaying.frame = cellFrame;
        }completion:^(BOOL bl){
        }];
    }else if( recognizer.state == UIGestureRecognizerStateEnded ){
        if( !dragging ){
            return;
        }
        dragging = NO;
        [UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationCurveEaseOut animations:^(void){
            CGRect frontFrame = frontCell.frame;
            frontFrame.origin.x = 0.5-self.frame.size.width;
            frontFrame.origin.y = -0.5f;
            frontCell.frame = frontFrame;
            CGRect cellFrame = cellPlaying.frame;
            cellFrame.origin.x = 0;
            cellPlaying.frame = cellFrame;
        }completion:^(BOOL bl){
            frontCell.hidden = YES;
            cellPlaying.hidden = NO;
            backCell.hidden = YES;
            frontCell.backgroundColor = [UIColor clearColor];
            backCell.backgroundColor = [UIColor clearColor];
            cellPlaying.backgroundColor = [UIColor clearColor];
        }];
    }else{
        CGPoint pt = [recognizer locationInView:self];
        if( dragging && pt.x > draggingPoint.x ){
            float dist = pt.x - draggingPoint.x;
            if( dist > self.frame.size.width / 4 ){
                if(jokeIndexPathDisplaying.row==0){
                    return;
                }
                dragging = NO;
                [UIView animateWithDuration:0.1 delay:0.0 options:UIViewAnimationCurveEaseOut animations:^(void){
                    CGRect frontFrame = frontCell.frame;
                    frontFrame.origin.x = 0.5f;
                    frontCell.frame = frontFrame;
                    CGRect cellFrame = cellPlaying.frame;
                    cellFrame.origin.x = 0;
                    cellPlaying.frame = cellFrame;
                }completion:^(BOOL bl){
                    [self dragRight];
                }];
            }else{
                CGRect frontFrame = frontCell.frame;
                frontFrame.origin.x = 0.5f-self.frame.size.width*3/4 + dist*1.5;
                frontCell.frame = frontFrame;
                CGRect cellFrame = cellPlaying.frame;
                cellFrame.origin.x = -self.frame.size.width/4 + dist;
                cellPlaying.frame = cellFrame;
            }
        }else if( dragging && draggingPoint.x > pt.x ){
            float dist = draggingPoint.x - pt.x;
            if( dist > self.frame.size.width / 4 ){
                if(jokeIndexPathDisplaying.row==jokeManagerPlaying.listShow.count - 1){
                    return;
                }
                dragging = NO;
                [UIView animateWithDuration:0.1 delay:0.0 options:UIViewAnimationCurveEaseOut animations:^(void){
                    CGRect frontFrame = frontCell.frame;
                    frontFrame.origin.x = 0.5-self.frame.size.width;
                    frontFrame.origin.y = -0.5f;
                    frontCell.frame = frontFrame;
                    CGRect cellFrame = cellPlaying.frame;
                    cellFrame.origin.x = -self.frame.size.width;
                    cellPlaying.frame = cellFrame;
                }completion:^(BOOL bl){
                    [self dragLeft];
                }];
            }else{
                CGRect frontFrame = frontCell.frame;
                frontFrame.origin.x = 0.5f-self.frame.size.width*3/4 - dist;
                frontCell.frame = frontFrame;
                CGRect cellFrame = cellPlaying.frame;
                cellFrame.origin.x = -self.frame.size.width/4 - dist*1.5;
                cellPlaying.frame = cellFrame;
            }
        }
    }
}

- (void)dragLeft {
    autoSelecting = NO;
    //展示层准备复位，去边去底
    cellPlaying.backgroundColor = [UIColor clearColor];
    CGRect cellFrame = cellPlaying.frame;
    cellFrame.origin.x = 0;
    cellPlaying.frame = cellFrame;
    
    mainTable.hidden = YES;
    CGPoint offset = mainTable.tableView.contentOffset;
    offset.y = offset.y + self.frame.size.width;
    mainTable.tableView.contentOffset = offset;
    
    //展示层已经复位，隐藏后层
    [UIView animateWithDuration:0.2 delay:0.0 options:UIViewAnimationCurveEaseOut animations:^(void){
        mainTable.alpha = 0.0f;
        indicator.frame = [self getIndicatorFrame:jokeIndexPathDisplaying.row+1];
    }completion:^(BOOL bl){
        mainTable.hidden = NO;
        mainTable.alpha = 1.0f;
        frontCell.hidden = YES;
        cellPlaying.hidden = NO;
        backCell.hidden = YES;
        frontCell.backgroundColor = [UIColor clearColor];
        backCell.backgroundColor = [UIColor clearColor];
        cellPlaying.backgroundColor = [UIColor clearColor];
        [self frontNback];
    }];
}

- (void)dragRight {
    autoSelecting = NO;
    
    CGRect cellFrame = cellPlaying.frame;
    cellFrame.origin.x = 0;
    cellPlaying.frame = cellFrame;
    
    cellPlaying.hidden = NO;
    backCell.hidden = YES;
    frontCell.backgroundColor = [UIColor clearColor];
    backCell.backgroundColor = [UIColor clearColor];
    cellPlaying.backgroundColor = [UIColor clearColor];
    
    CGPoint offset = mainTable.tableView.contentOffset;
    offset.y = offset.y - self.frame.size.width;
    mainTable.tableView.contentOffset = offset;
    
    [UIView animateWithDuration:0.2 delay:0.0 options:UIViewAnimationCurveEaseOut animations:^(void){
        frontCell.alpha = 0.99f;
        indicator.frame = [self getIndicatorFrame:jokeIndexPathDisplaying.row-1];
    }completion:^(BOOL bl){
        frontCell.hidden = YES;
        frontCell.alpha = 1.0f;
        [self frontNback];
    }];
}

- (void)frontNback {
    if(jokeManagerPlaying.listShow.count==0 || jokeIndexPathDisplaying.row<=0){
        frontCell.alpha = 0.0f;
    }else{
        frontCell.alpha = 1.0f;
        int newRow = jokeIndexPathDisplaying.row-1;
        NSIndexPath *leftPath = [NSIndexPath indexPathForRow:newRow inSection:jokeIndexPathDisplaying.section];
        JokeModel *tJoke = [jokeManagerPlaying.listShow objectAtIndex:leftPath.row];
        [frontCell setData:owner :tJoke :jokeManagerPlaying];
    }
    CGRect leftFrame = frontCell.frame;
    leftFrame.origin.x = 0.5f-self.frame.size.width;
    leftFrame.origin.y = -0.5f;
    frontCell.frame = leftFrame;
    frontCell.hidden = YES;
    frontCell.backgroundColor = UIColorFromRGB(0xebeef0, 1.0f);
    
    if(jokeManagerPlaying.listShow.count==0 || jokeIndexPathDisplaying.row>=jokeManagerPlaying.listShow.count - 1 ){
        backCell.alpha = 0.0f;
    }else{
        backCell.alpha = 1.0f;
        int newRow = jokeIndexPathDisplaying.row+1;
        NSIndexPath *leftPath = [NSIndexPath indexPathForRow:newRow inSection:jokeIndexPathDisplaying.section];
        JokeModel *tJoke = [jokeManagerPlaying.listShow objectAtIndex:leftPath.row];
        [backCell setData:owner :tJoke :jokeManagerPlaying];
    }
    //后层cell放到正位
    CGRect rightFrame = backCell.frame;
    rightFrame.origin.x = 0.5f;
    rightFrame.origin.y = -0.5f;
    backCell.frame = rightFrame;
    backCell.hidden = YES;
    backCell.backgroundColor = UIColorFromRGB(0xebeef0, 1.0f);
}

- (CGRect)getIndicatorFrame:(int)newRow {
    CGRect indicatorFrame = indicator.frame;
    int count = jokeManagerPlaying.listShow.count;
    float newWidth = 40;
    if( count > 0 ){
        newWidth = self.frame.size.width / count;
        newWidth = newWidth < 40 ? 40 : newWidth;
    }
    indicatorFrame.size.width = newWidth;
    
    float leftEnd = indicatorFrame.size.width/2 + 5;
    float rightEnd = self.frame.size.width - indicatorFrame.size.width/2 - 5;
    
    if( jokeManagerPlaying.listShow.count <= 1 ){
        indicator.hidden = YES;
    }else{
        indicator.hidden = NO;
    }
    
    int index = jokeManagerPlaying.listShow.count>1?(jokeManagerPlaying.listShow.count-1):1;
    float dist = (rightEnd-leftEnd)/index;
    indicatorFrame.origin.x = leftEnd + newRow*dist - indicatorFrame.size.width/2;
    return indicatorFrame;
}

#pragma mark -
#pragma mark -------状态机-------

- (void)setUserState:(JPVUserStateBase *)newState {
    dispatch_async(dispatch_get_main_queue(), ^{
        currentUserState = newState;
        [currentUserState JPVUScell];
    });
}

- (void)reload:(JokeManager *)pJokeManager :(NSIndexPath *)pJokeIndexPath {
    if( pJokeManager != jokeManagerPlaying ){
        self.jokeManagerPlaying = pJokeManager;
        [mainTable.tableView reloadData];
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        Log(@"JPV reload sort : %d, display joke : %d",pJokeManager.sortIndex, pJokeIndexPath.row);
        autoSelecting = YES;
        CGPoint offset = mainTable.contentOffset;
        offset.x = mainTable.tableView.frame.size.width * pJokeIndexPath.row;
        mainTable.contentOffset = offset;
        indicator.frame = [self getIndicatorFrame:pJokeIndexPath.row];
    });
}

- (void)doneNew:(JokeManager *)pJokeManager :(int)newCount {
    Log(@"JPV doneNew :%d",newCount);
    if( pJokeManager != jokeManagerPlaying ){
        return;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        autoSelecting = YES;
        [mainTable.tableView reloadData];
        if( newCount != 0 ){
            CGPoint offset = mainTable.contentOffset;
            offset.x = 0;
            mainTable.contentOffset = offset;
            indicator.frame = [self getIndicatorFrame:0];
        }
    });
}

- (void)doneNext:(JokeManager *)pJokeManager :(int)nextCount {
    if( pJokeManager != jokeManagerPlaying ){
        return;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        autoSelecting = YES;
        [mainTable.tableView reloadData];
        indicator.frame = [self getIndicatorFrame:jokeIndexPathDisplaying.row];
    });
}

- (void)doneNewAndNext:(JokeManager *)pJokeManager :(int)newCount :(int)nextCount {
    Log(@"JPV doneNewAndNext :%d",newCount);
    if( pJokeManager != jokeManagerPlaying ){
        return;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        autoSelecting = YES;
        [mainTable.tableView reloadData];
        if( newCount != 0 ){
            CGPoint offset = mainTable.contentOffset;
            offset.x = 0;
            mainTable.contentOffset = offset;
            indicator.frame = [self getIndicatorFrame:0];
        } else {
            if( nextCount != 0 ){
                indicator.frame = [self getIndicatorFrame:jokeIndexPathDisplaying.row];
            }else{
                //nothing
            }
        }
    });
}

- (void)zoomIn {
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:0.1 delay:0.1 options:UIViewAnimationCurveEaseOut animations:^(void){
            CGRect barFrame = jokeActionBarContainer.frame;
            barFrame.origin.y = barFrame.origin.y + barFrame.size.height;
            jokeActionBarContainer.frame = barFrame;
        }completion:^(BOOL bl){
            [owner.navigationController setNavigationBarHidden:YES animated:YES];
        }];
        [UIView animateWithDuration:0.5 delay:0.0 options:UIViewAnimationCurveEaseOut animations:^(void){
            CGAffineTransform currentTransform = mainTableContainer.transform;
            CGAffineTransform newTransform = CGAffineTransformScale(currentTransform, 0.5f, 0.5f);
            mainTableContainer.transform = newTransform;
            CGRect tableFrame = mainTableContainer.frame;
            tableFrame.origin.y = 20;
            mainTableContainer.frame = tableFrame;
        }completion:^(BOOL bl){
        }];
    });
}

- (void)zoomOut {
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:0.4 delay:0.2 options:UIViewAnimationCurveEaseIn animations:^(void){
            CGAffineTransform currentTableTransform = mainTableContainer.transform;
            CGAffineTransform newTableTransform = CGAffineTransformScale(currentTableTransform, 2.0f, 2.0f);
            mainTableContainer.transform = newTableTransform;
            CGRect tableFrame = mainTableContainer.frame;
            tableFrame.origin.y = 0;
            mainTableContainer.frame = tableFrame;
            CGRect barFrame = jokeActionBarContainer.frame;
            barFrame.origin.y = barFrame.origin.y - barFrame.size.height;
            jokeActionBarContainer.frame = barFrame;
            [owner.navigationController setNavigationBarHidden:NO animated:NO];
        }completion:^(BOOL bl){
        }];
    });
}

- (void)hideBar {
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.3];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
        CGRect barFrame = jokeActionBarContainer.frame;
        barFrame.origin.y = barFrame.origin.y + barFrame.size.height;
        jokeActionBarContainer.frame = barFrame;
        [UIView commitAnimations];
    });
}

- (void)showBar {
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.3];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
        CGRect barFrame = jokeActionBarContainer.frame;
        barFrame.origin.y = barFrame.origin.y - barFrame.size.height;
        jokeActionBarContainer.frame = barFrame;
        [UIView commitAnimations];
    });
}

#pragma mark -
#pragma mark EasyTableViewDelegate

- (NSUInteger)numberOfSectionsInEasyTableView:(EasyTableView*)easyTableView {
    return 1;
}

- (NSUInteger)numberOfCellsForEasyTableView:(EasyTableView *)view inSection:(NSInteger)section {
    if(jokeManagerPlaying==nil||jokeManagerPlaying.listShow==nil){
        return 0;
    }else{
        //        Log(@"count :%d",[jokeManagerPlaying.listShow count]);
        return [jokeManagerPlaying.listShow count];
    }
}

//// The height of the footer section view MUST be the same as your HORIZONTAL_TABLEVIEW_HEIGHT (horizontal EasyTableView only)
//- (UIView *)easyTableView:(EasyTableView*)easyTableView viewForFooterInSection:(NSInteger)section {
//    Log(@"test7");
//    UILabel *label = [[UILabel alloc] init];
//	label.textAlignment = UITextAlignmentCenter;
//	label.frame = CGRectMake(0, 0, 30, mainTable.tableView.frame.size.height);
//    label.backgroundColor = [UIColor clearColor];
//    return label;
//}
//
//// The height of the footer section view MUST be the same as your HORIZONTAL_TABLEVIEW_HEIGHT (horizontal EasyTableView only)
//- (UIView *)easyTableView:(EasyTableView*)easyTableView viewForHeaderInSection:(NSInteger)section {
//    UILabel *label = [[UILabel alloc] init];
//	label.textAlignment = UITextAlignmentCenter;
//	label.frame = CGRectMake(0, 0, 30, mainTable.tableView.frame.size.height);
//    label.backgroundColor = [UIColor clearColor];
//    return label;
//}

// These delegate methods support both example views - first delegate method creates the necessary views
- (UIView *)easyTableView:(EasyTableView *)easyTableView viewForRect:(CGRect)rect {
    NSArray *viewNibList = [[NSBundle mainBundle] loadNibNamed:@"JokePageCell" owner:self options:nil];
    UIView *view = [[viewNibList objectAtIndex:0] retain];
    return view;
}

// Second delegate populates the views with data from a data source
- (void)easyTableView:(EasyTableView *)easyTableView setDataForView:(UIView *)view forIndexPath:(NSIndexPath *)indexPath {
    [owner baseHideComment];
    JokeModel *tJoke = [jokeManagerPlaying.listShow objectAtIndex:indexPath.row];
    cellPlaying = (JokePageCell *)view;
    [cellPlaying setData:owner :tJoke :jokeManagerPlaying];
    [cellPlaying toTop];
    [cellPlaying setMoreData];
    
    [currentUserState JPVUScell];
    
    self.jokeIndexPathDisplaying = [indexPath copy];
    if( autoSelecting ){
        [self frontNback];
    }else{
        [owner JPVselect:jokeManagerPlaying :jokeIndexPathDisplaying];
    }
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        tJoke.read = YES;
        [[DBManager sharedInstance] updateJoke:jokeManagerPlaying.dbSort :tJoke];
    });
}

- (void)startComment {
    [owner baseShowComment];
}

- (void)startFavorite {
    ;
}

- (void)BVCcommentDone:(HPGrowingTextView *)commentField {
    Log(@"commentField.text:%@ , count:%d",commentField.text,[commentField.text length]);
    if ([commentField.text length] == 0) {
        [owner baseShowInfoHud:NSLocalizedString(@"随便说点什么吧", @"") andIsTop:YES];
        return;
    }
    
    NSString *tText = [commentField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet ]];//去掉首尾空格
    if ([tText length] == 0) {
        [owner baseShowInfoHud:NSLocalizedString(@"元方,空格你怎么看?", @"") andIsTop:YES];
        return;
    }
    
    [commentField resignFirstResponder];
    HAS_NO_NETWORK(owner);
    
    MBProgressHUD *hudLoading = [MBProgressHUD showHUDAddedTo:owner.view animated:YES];
    hudLoading.labelText = @"正在发表...";
    hudLoading.opacity = PP_mbprogressHudOpacity;
    NSString *jokeId = [[cellPlaying.jokePlaying.jokeId copy] autorelease];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:[NSURL URLWithString:JOKE_SEND_COMMENT]];
//        request.userAgentString = @"lxh_app2_100";
//        [request addRequestHeader:@"Cookie" value:[NSString stringWithFormat:@"webpy_session_id=%@",[UserManager sharedInstance].sessionId] ];
//        [request setPostValue:@"post_comment" forKey:@"action"];
//        [request setPostValue:[[NSString alloc]initWithFormat:@"%@",jokeId] forKey:@"joke_id"];
//        [request setPostValue:[[NSString alloc]initWithFormat:@"%@",jokeId] forKey:@"gather_id"];
//        [request setPostValue:commentField.text forKey:@"content"];
//        [request setDelegate:self];
//        [request startSynchronous];
        
        ASIFormDataRequest_POST(JOKE_SEND_COMMENT);
        [request setPostValue:@"post_comment" forKey:@"action"];
        [request setPostValue:[[NSString alloc]initWithFormat:@"%@",jokeId] forKey:@"joke_id"];
        [request setPostValue:[[NSString alloc]initWithFormat:@"%@",jokeId] forKey:@"gather_id"];
        [request setPostValue:commentField.text forKey:@"content"];
        [request setDelegate:self];
        [request startSynchronous];

        NSError *error = [request error];
        NSString *res = nil;
        if(!error){
            NSString *tResponseStr = [request responseString];
            Log(@"res: %@",tResponseStr);
            SBJsonParser *tJsonParser = [[SBJsonParser alloc] init];
            id tJsonObjects = [tJsonParser objectWithString:tResponseStr];
            [tJsonParser release], tJsonParser = nil;
            if ([tJsonObjects isKindOfClass:[NSDictionary class]]){
                BOOL is_success = [[(NSDictionary *)tJsonObjects objectForKey:@"success"] boolValue];
                if (is_success) {
                    NSString *username = [(NSDictionary *)tJsonObjects objectForKey:@"author_user_name"];
                    Log(@"done. username: %@",username);
                    JokeReplyModel *one = [[[JokeReplyModel alloc] init] autorelease];
                    [one setReplyName:username];
                    [one setReplyText:commentField.text];
                    if( [jokeId isEqualToString:cellPlaying.jokePlaying.jokeId]){
                        [cellPlaying.jokePlaying.replies addObject:one];
                        cellPlaying.jokePlaying.replyNum++;
                        [[DBManager sharedInstance] updateJoke:jokeManagerPlaying.dbSort :cellPlaying.jokePlaying];
                    }
                    dispatch_async(dispatch_get_main_queue(), ^{
//                        [owner baseShowInfoHud:NSLocalizedString(@"发表评论成功", @"") andIsTop:YES];
                        
                        hudLoading.customView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"37x-Checkmark.png"]] autorelease];
                        hudLoading.labelText = @"发表评论成功";
                        hudLoading.mode = MBProgressHUDModeCustomView;
                        [hudLoading hide:YES afterDelay:0.5];
                        commentField.text = @"";
                        [cellPlaying reply];
                    });
                    return;
                }else {
                    res = [(NSDictionary *)tJsonObjects objectForKey:@"error"];
                    Log ( @"failed: %@",res);
                }
            }else{
                res = @"服务器出错，请稍后再试";
                Log ( @"failed: %@",res);
            }
        }else{
            Log ( @"failed: %@",[error description]);
            res = @"网络异常,请稍后再试";
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            hudLoading.customView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"37x-Wrong.png"]] autorelease];
            hudLoading.labelText = res;
            hudLoading.mode = MBProgressHUDModeCustomView;
            [hudLoading hide:YES afterDelay:0.5];
        });
    });
}

- (void)BVCcommentHide:(UIView *)commentView {
}

#pragma mark -
#pragma mark -------JokeActionBarDelegate 协议方法-------

- (void)JABshare {
    Log(@"MARK");
    [owner JPVshare];
}

- (void)JABcomment {
    [currentUserState JPVUScomment];
}

- (void)JABfavorite {
    HAS_NO_NETWORK(owner);
    [currentUserState JPVUSfavorite];
}

@end

#pragma mark -------登录状态机 -------

@implementation JPVUserStateBase
-(id)init:(JokePageView *)powner {
    self = [super init];
    if (self) {
        owner = powner;
    }
    return self;
}
@end

@implementation JPVUserStateLogin:JPVUserStateBase
-(void)JPVUScomment{
    [owner startComment];
}
-(void)JPVUSfavorite{
    [owner startFavorite];
}
-(void)JPVUScell{
    [owner.cellPlaying setUserState:owner.cellPlaying.userStateLogin];
}
@end

@implementation JPVUserStateLogout:JPVUserStateBase
-(void)JPVUScomment{
    [owner.owner JPVlogin];
}
-(void)JPVUSfavorite{
    [owner.owner JPVlogin];
}
-(void)JPVUScell{
    [owner.cellPlaying setUserState:owner.cellPlaying.userStateLogout];
}
@end


//#pragma mark -
//#pragma mark -------touches 基类方法-------
//
//- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
//    UITouch* touch = [touches anyObject];
//    CGPoint pt = [touch locationInView:self];
//    if(CGRectContainsPoint(owner.baseCommentView.frame,pt)){
//        return;
//    }
//    [owner baseHideComment];
//    
//    CGRect jumperFrame = jumper.frame;
//    jumperFrame.origin.y = pt.y-jumperFrame.size.height/2;
//    jumper.frame = jumperFrame;
//    
//    jumper.alpha = 1.0f;
//    
//    CGRect fingerFrame = finger.frame;
//    fingerFrame.origin.x = pt.x - fingerFrame.size.width/2;
//    finger.frame = fingerFrame;
//    leftArrow.alpha = 0.0f;
//    rightArrow.alpha = 0.0f;
//    finger.alpha = 0.0f;
//    
//    jumpingPoint = pt;
//}
//
//- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
//    UITouch *touch = [[event allTouches] anyObject];
//    CGPoint pt = [touch locationInView:self];
//    if(CGRectContainsPoint(owner.baseCommentView.frame,pt)){
//        return;
//    }
//    float dx = abs(pt.x-jumpingPoint.x);
//    float dy = abs(pt.y-jumpingPoint.y);
//    float ang = atan2(dy,dx);
//    if( ang > 0.45 ){
//        leftArrow.alpha = 0.0f;
//        rightArrow.alpha = 0.0f;
//        finger.alpha = 0.0f;
//        return;
//    }
//    //    Log(@"angle : %f",ang);
//    
//    if( jumping){
//        float targetX = pt.x - finger.frame.size.width/2;
//        CGRect fingerFrame = finger.frame;
//        fingerFrame.origin.x = targetX;
//        finger.frame = fingerFrame;
//    }
//    
//    float halfWidth = self.frame.size.width/2;
//    if(pt.x > leftArrow.frame.size.width && pt.x < rightArrow.frame.origin.x){
//        jumping = YES;
//        float leftAlpha = 1-pt.x/self.frame.size.width;
//        float rightAlpha = pt.x/self.frame.size.width;
//        float fingerAlpha = abs(halfWidth-pt.x)/(halfWidth);
//        fingerAlpha = (fingerAlpha>0.2)?((fingerAlpha-0.2)/0.8):0.0;
//        leftArrow.alpha = leftAlpha;
//        rightArrow.alpha = rightAlpha;
//        finger.alpha = fingerAlpha;
//    }else
//        
//        if( pt.x>jumpingPoint.x && pt.x-jumpingPoint.x>100){
//            leftArrow.alpha = 0.0f;
//            rightArrow.alpha = 0.0f;
//            if(jumping){
//                jumping = NO;
//                [self touchesLeft];
//            }
//        }else if(jumpingPoint.x>pt.x && jumpingPoint.x-pt.x>100){
//            leftArrow.alpha = 0.0f;
//            rightArrow.alpha = 0.0f;
//            if(jumping){
//                jumping = NO;
//                [self touchesRight];
//            }
//        }else{
//            jumping = YES;
//        }
//}
//
//- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
//    if( jumping ){
//        jumper.alpha = 0.0f;
//    }
//    jumping = NO;
//}
//
//- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
//    jumper.alpha = 0.0f;
//    jumping = NO;
//}
//
//- (void)touchesLeft {
//    autoSelecting = NO;
//    if(jokeIndexPathDisplaying.row==0){
//        [UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationCurveEaseOut animations:^(void){
//            CGRect fingerFrame = finger.frame;
//            fingerFrame.origin.x = self.frame.size.width/2 - fingerFrame.size.width/2;
//            finger.frame = fingerFrame;
//        }completion:^(BOOL bl){
//            jumper.alpha = 0.0f;
//            [owner baseShowInfoHud:@"已经是最新一篇" andIsTop:NO];
//        }];
//        return;
//    }
//    
//    int newRow = jokeIndexPathDisplaying.row-1;
//    NSIndexPath *leftPath = [NSIndexPath indexPathForRow:newRow inSection:jokeIndexPathDisplaying.section];
//    JokeModel *tJoke = [jokeManagerPlaying.listShow objectAtIndex:leftPath.row];
//    [frontCell setData:owner :self :tJoke :jokeManagerPlaying];
//    
//    CGRect leftFrame = frontCell.frame;
//    leftFrame.origin.x = -self.frame.size.width;
//    frontCell.frame = leftFrame;
//    frontCell.hidden = NO;
//    frontCell.backgroundColor = UIColorFromRGB(0xebeef0, 1.0f);
//    
//    [UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationCurveEaseOut animations:^(void){
//        CGRect leftFrame = frontCell.frame;
//        leftFrame.origin.x = 0.5f;
//        leftFrame.origin.y = -0.5f;
//        frontCell.frame = leftFrame;
//        CGRect fingerFrame = finger.frame;
//        fingerFrame.origin.x = self.frame.size.width/2 - fingerFrame.size.width/2;
//        finger.frame = fingerFrame;
//        indicator.frame = [self getIndicatorFrame:newRow];
//    }completion:^(BOOL bl){
//        jumper.alpha = 0.0f;
//        frontCell.backgroundColor = [UIColor clearColor];
//        CGPoint offset = mainTable.tableView.contentOffset;
//        offset.y = offset.y - self.frame.size.width;
//        mainTable.tableView.contentOffset = offset;
//        
//        [UIView animateWithDuration:0.2 delay:0.0 options:UIViewAnimationCurveEaseOut animations:^(void){
//            frontCell.alpha = 0.99f;
//        }completion:^(BOOL bl){
//            frontCell.hidden = YES;
//            frontCell.alpha = 1.0f;
//        }];
//    }];
//}
//
//- (void)touchesRight {
//    autoSelecting = NO;
//    if(jokeIndexPathDisplaying.row==jokeManagerPlaying.listShow.count - 1){
//        [UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationCurveEaseOut animations:^(void){
//            CGRect fingerFrame = finger.frame;
//            fingerFrame.origin.x = self.frame.size.width/2 - fingerFrame.size.width/2;
//            finger.frame = fingerFrame;
//        }completion:^(BOOL bl){
//            jumper.alpha = 0.0f;
//            [owner baseShowInfoHud:@"已经是最后一篇" andIsTop:NO];
//        }];
//        return;
//    }
//    
//    //后层的cell先加载数据
//    int newRow = jokeIndexPathDisplaying.row+1;
//    NSIndexPath *rightPath = [NSIndexPath indexPathForRow:newRow inSection:jokeIndexPathDisplaying.section];
//    JokeModel *tJoke = [jokeManagerPlaying.listShow objectAtIndex:rightPath.row];
//    [backCell setData:owner :self :tJoke :jokeManagerPlaying];
//    //把mainTable拎到展示层
//    //    [mainTableContainer bringSubviewToFront:mainTable];
//    //后层cell放到正位
//    CGRect rightFrame = backCell.frame;
//    rightFrame.origin.x = 0.5f;
//    rightFrame.origin.y = -0.5f;
//    backCell.frame = rightFrame;
//    backCell.hidden = NO;
//    //展示层准备滑动，加边加底
//    cellPlaying.backgroundColor = UIColorFromRGB(0xebeef0, 1.0f);
//    [UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationCurveEaseOut animations:^(void){
//        //展示层移动
//        CGRect cellFrame = cellPlaying.frame;
//        cellFrame.origin.x = -self.frame.size.width;
//        cellPlaying.frame = cellFrame;
//        CGRect fingerFrame = finger.frame;
//        fingerFrame.origin.x = self.frame.size.width/2 - fingerFrame.size.width/2;
//        finger.frame = fingerFrame;
//        indicator.frame = [self getIndicatorFrame:newRow];
//    }completion:^(BOOL bl){
//        jumper.alpha = 0.0f;
//        //展示层准备复位，去边去底
//        cellPlaying.backgroundColor = [UIColor clearColor];
//        mainTable.hidden = YES;
//        CGRect cellFrame = cellPlaying.frame;
//        cellFrame.origin.x = 0;
//        cellPlaying.frame = cellFrame;
//        CGPoint offset = mainTable.tableView.contentOffset;
//        offset.y = offset.y + self.frame.size.width;
//        mainTable.tableView.contentOffset = offset;
//        //展示层已经复位，隐藏后层
//        [UIView animateWithDuration:0.2 delay:0.0 options:UIViewAnimationCurveEaseOut animations:^(void){
//            mainTable.alpha = 0.0f;
//        }completion:^(BOOL bl){
//            mainTable.hidden = NO;
//            mainTable.alpha = 1.0f;
//            backCell.hidden = YES;
//        }];
//    }];
//}
